//
//  YLProductViewController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/8/24.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLProductViewController.h"
#import "XXPageTabView.h"
#import "XXPageTabItemLable.h"
#import <Masonry.h>
#import "GSFilterView.h"
#import "GSMacros.h"
#import "YLFundListController.h"
#import "YLGlobeHeader.h"
#import "PXAlertView.h"
#import "YLFilterViewModel.h"
#import "WHProgressHUD.h"
#import "YLProjectListController.h"
#import "YLRegularFinancingListController.h"
#import "YLFundListController.h"
#import "YLCertifiedPaymentViewController.h"
#import "YLAccountTool.h"
#import "YLRiskAssessmentController.h"
#import "YLAdView.h"
#import "YLAdViewModel.h"
#import "YLAdModel.h"
#import "WHWebViewController.h"
#import "YLQualificationSureView.h"
@interface YLProductViewController ()<XXPageTabViewDelegate, DKFilterViewDelegate,YLProductListControllerDelegate,YLQualificationSureViewDelegate>
@property (nonatomic, strong) XXPageTabView *pageTabView;
@property (nonatomic,strong) GSFilterView *filterView;
@property (nonatomic,strong) DKFilterModel *clickModel;
@property (nonatomic, weak) UIView *baseView;
@property (nonatomic, strong) YLFilterViewModel *filterViewModel;

@property (nonatomic, weak) UIButton *projectButton;
@property (nonatomic, strong) YLAdViewModel *adViewModel;
@end

@implementation YLProductViewController

- (YLFilterViewModel *)filterViewModel
{
    if (!_filterViewModel) {
        _filterViewModel = [[YLFilterViewModel alloc] init];
    }
    return _filterViewModel;
}

- (YLAdViewModel *)adViewModel
{
    if (!_adViewModel) {
        _adViewModel = [[YLAdViewModel alloc] init];
        _adViewModel.conditionId = 12;
    }
    return _adViewModel;
}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"产品";
    
    if (_pageTabView) {
        return;
    }
    
    __weak typeof(self) weakSelf = self;
    [[self.adViewModel.requestCommand execute:nil] subscribeNext:^(id  _Nullable x) {
        YLAdModel *model = x;
        YLAdView *adView = [[YLAdView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        adView.iconUrl = model.noticeIcon;
        [[UIApplication sharedApplication].keyWindow addSubview:adView];
        adView.clickBlock = ^{
            WHWebViewController *webCon = [[WHWebViewController alloc] init];
            [weakSelf.navigationController pushViewController:webCon animated:YES];
        };
    }];
   
    [self setUpPageTabView];
    
    [self setUpUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadData) name:@"YLLoadMyInfoNoti" object:nil];
    
}

#pragma mark 弹出风险评测
- (void)popRiskEvaluation:(NSString *)title
{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"风险提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不了,谢谢" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    __weak typeof(self) weakSelf = self;
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的，测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        YLRiskAssessmentController *risk = [[YLRiskAssessmentController alloc] init];
        [weakSelf.navigationController pushViewController:risk animated:YES];
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)setUpPageTabView
{
    YLRegularFinancingListController *vc1 = [[YLRegularFinancingListController alloc] init];
    vc1.delegate = self;
    vc1.searchPayCategory = -1;
    vc1.yieldFrom = -1;
    vc1.yieldTo = -1;
    vc1.searchProductTerm = -1;
    vc1.searchProductCategory = -1;
    
    YLFundListController *vc2 = [[YLFundListController alloc] init];
    vc2.delegate = self;
    vc2.productType = -1;
    vc2.duration = -1;
    vc2.operationMode = -1;
    
    [self addChildViewController:vc1];
    [self addChildViewController:vc2];
    
    //支持网易云音乐，今日头条，微博等切换栏效果
    self.pageTabView = [[XXPageTabView alloc] initWithChildControllers:self.childViewControllers childTitles:@[@"普惠", @"银来基金"]];
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    
    CGFloat y = self.navigationController.navigationBar.frame.size.height + rectStatus.size.height;
    
    self.pageTabView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-y - 44 );
    self.pageTabView.tabSize = CGSizeMake(YLScreenW, 44.0f);
    self.pageTabView.selectedColor = YLLOrgColor;
    self.pageTabView.separatorColor = YLColor(200, 200, 200);
    self.pageTabView.unSelectedColor = YLLineColor;
    self.pageTabView.delegate = self;
    self.pageTabView.indicatorHeight = 1.5;
    self.pageTabView.titleStyle = XXPageTabTitleStyleDefault;
    self.pageTabView.indicatorStyle = XXPageTabIndicatorStyleStretch;
    self.pageTabView.indicatorWidth = YLScreenW / 2.0 - 30;
    [self.view addSubview:self.pageTabView];
    
    UIButton *projectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:projectButton];
    [projectButton setBackgroundImage:[UIImage imageNamed:@"productImage"] forState:UIControlStateNormal];
    _projectButton = projectButton;
    __weak typeof(self) weakSelf = self;
    [projectButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view.mas_right).mas_offset(-10);
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-80);
        make.height.width.mas_equalTo(65);
    }];
    [[projectButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        YLProjectListController *project = [[YLProjectListController alloc] init];
        [weakSelf.navigationController pushViewController:project animated:YES];
    }];
}

- (void)setUpUI
{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"choice"] style:UIBarButtonItemStylePlain target:self action:@selector(choice)];
    
    self.view.backgroundColor = [UIColor whiteColor];
}



- (void)popChoiceView
{
    __weak typeof(self) weakSelf = self;
    
        UIView *baseView = [[UIView alloc] init];
        [self.view addSubview:baseView];
        _baseView = baseView;
        
        [baseView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.left.mas_equalTo(weakSelf.view);
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-weakSelf.view.frame.size.height);
            make.height.mas_equalTo(weakSelf.view.frame.size.height);
        }];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
            [weakSelf choice];
        }];

        [weakSelf.baseView addGestureRecognizer:tap];
    
        self.filterView = [[GSFilterView alloc] init];
    
    
    
        [self.baseView addSubview:self.filterView];
    
    
        [self.filterView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(weakSelf.baseView);
            make.top.mas_equalTo(weakSelf.baseView);
            make.height.mas_equalTo(400);
        }];
    
  //  UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] init];
    [self.filterView addGestureRecognizer:tap1];
    
    //[self.filterView addSubview:button];
 
        
        self.filterView.delegate = self;
        
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [button1 addTarget:self action:@selector(again) forControlEvents:UIControlEventTouchUpInside];
        button1.backgroundColor = YLColor(228, 146, 42);
        [self.baseView addSubview:button1];
        [button1 setTitle:@"重 置" forState:UIControlStateNormal];
        [button1 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(weakSelf.baseView);
            make.top.mas_equalTo(weakSelf.filterView.mas_bottom);
            make.height.mas_equalTo(44);
        }];
        
        UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
        button2.backgroundColor = YLMainColor;
        [self.baseView addSubview:button2];
        [button2 setTitle:@"确 认" forState:UIControlStateNormal];
        [button2 addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchDown];
        [button2 mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(weakSelf.baseView);
            make.left.mas_equalTo(button1.mas_right);
            make.width.mas_equalTo(button1.mas_width);
            make.top.mas_equalTo(weakSelf.filterView.mas_bottom);
            make.height.mas_equalTo(44);
        }];

    
    if ((int)self.pageTabView.selectedTabIndex == 0) {
        [self.filterView setFilterModels:self.filterViewModel.productModels];
    } else {
        [self.filterView setFilterModels:self.filterViewModel.fundModels];
    }
    
    [self.view layoutIfNeeded];
    
    if ((int)self.pageTabView.selectedTabIndex == 0) {
        self.filterView.selectedButtons = self.filterViewModel.producTags;
    } else {
        self.filterView.selectedButtons = self.filterViewModel.fundTags;
    }
    
    [_baseView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(weakSelf.view);
    }];
    
    [UIView animateWithDuration:1.0f animations:^{
        [weakSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.5f animations:^{
            weakSelf.baseView.backgroundColor = YLColorA(70, 70, 70, 0.4);
            
        } ];
    }];
    
}

- (void)selectedIndex:(NSInteger)index
{
    
    if (self.pageTabView) {
        self.pageTabView.selectedTabIndex = index;
    }

}

- (void)dismissChoiceView
{

    __weak typeof(self) weakSelf = self;
    self.baseView.backgroundColor = [UIColor clearColor];
    [self.view layoutIfNeeded];
    
    [_baseView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-weakSelf.view.frame.size.height);
    }];
    
    [UIView animateWithDuration:0.5f animations:^{
        [weakSelf.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [weakSelf.baseView removeFromSuperview];
        weakSelf.baseView = nil;
    }];
}

- (void)choice
{
    if (!_baseView) {
        [self popChoiceView];
    } else {
      [self dismissChoiceView];
    }
}

- (void)again
{
    [self.filterView choiceAgain];
}

- (void)sure
{
    NSString *result = @"";
    
    // 定期理财
    if ((int)self.pageTabView.selectedTabIndex == 0) {
        for (NSInteger i = 0; i < self.filterView.filterModels.count; i ++) {
            
            DKFilterModel *model = self.filterView.filterModels[i];
            if(model == self.clickModel){
                continue;
            }
            
            NSArray *array = [model getFilterResult];

            NSString *str = array.firstObject;
            
            if ([model.elements containsObject:str]) {
                
                NSInteger index = [model.elements indexOfObject:str];
                
                self.filterViewModel.producTags[i] = @(index);
            }
            
        }
        
        [self setProductController];
        
        for (DKFilterModel *model in self.filterView.filterModels) {
            
            result = [result stringByAppendingFormat:@"所属标题:%@\n",model.title];
            
            result = [result stringByAppendingString:@"\n"];
        }
        
        
        
    } else {
        for (NSInteger i = 0; i < self.filterView.filterModels.count; i ++) {
            DKFilterModel *model = self.filterView.filterModels[i];
            if(model == self.clickModel){
                continue;
            }
            NSArray *array = [model getFilterResult];
            NSString *str = array.firstObject;
            
            if ([model.elements containsObject:str]) {
                
                NSInteger index = [model.elements indexOfObject:str];
                
                self.filterViewModel.fundTags[i] = @(index);
            }
            
        }
        [self setFuncListController];
    }
    
    [self choice];
}

- (void)loadData
{
    [self.pageTabView setSelectedTabIndexWithAnimation:1];
    YLFundListController *list = self.childViewControllers.lastObject;
    [list loadNewData];
}

- (void)setFuncListController
{
    YLFundListController *productList = self.childViewControllers.lastObject;
    NSArray *tags = self.filterViewModel.fundTags;
    DKFilterModel *model = nil;
    // 产品类型
    {
        model  = self.filterView.filterModels.firstObject;
        
        NSInteger tag =  [model.elementTags[[tags.firstObject integerValue]] integerValue];
        productList.productType = tag;
    }
    
    {
        model  = self.filterView.filterModels[1];
        
        NSInteger tag =  [model.elementTags[[tags[1] integerValue]] integerValue];
        productList.duration = tag;
    }
    
    {
        model  = self.filterView.filterModels.lastObject;
        
        NSInteger tag =  [model.elementTags[[tags[2] integerValue]] integerValue];
        productList.operationMode = tag;
    }
    
    [productList loadNewData];
}

- (void)setProductController
{
    // 可以在加一个tag数组 用这个数组记录tag值
    // productags 里的下标  取出每个tag数组中的值
    YLRegularFinancingListController *productList = self.childViewControllers.firstObject;
    NSArray *tags = self.filterViewModel.producTags;
    DKFilterModel *model = nil;
    // 兑换方式
    {
        model  = self.filterView.filterModels.firstObject;
        
        NSInteger tag =  [model.elementTags[[tags.firstObject integerValue]] integerValue];
    
        productList.searchPayCategory = tag;
    }
    
    // 年化
    {
        model  = self.filterView.filterModels[1];
        
        NSInteger tag =  [model.elementTags[[tags[1] integerValue]] integerValue];
        
        switch (tag) {
            case -1:
                productList.yieldFrom = -1;
                productList.yieldTo = -1;
                break;
                
            case 0:
                productList.yieldFrom = 6;
                productList.yieldTo = 9;
                break;
                
            case 1:
                productList.yieldFrom = 9;
                productList.yieldTo = 12;
                break;
                
            case 2:
                productList.yieldFrom = 12;
                productList.yieldTo = 16;
                break;
                
            case 3:
                productList.yieldFrom = 16;
                productList.yieldTo = 100;
            default:
                break;
        }
        
        
    }
    
    // 产品期限
    {
        model  = self.filterView.filterModels[2];
        
        NSInteger tag =  [model.elementTags[[tags[2] integerValue]] integerValue];
        
        productList.searchProductTerm = tag;
    }
    
    // 产品类型
    {
        model  = self.filterView.filterModels[3];
        
        NSInteger tag =  [model.elementTags[[tags[3] integerValue]] integerValue];
        productList.searchProductCategory = tag;
    }
    
    [productList loadNewData];

}

- (void)productListControllerShowButton:(YLProductListController *)controller
{
    __weak typeof(self) weakSelf = self;
    [_projectButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(weakSelf.view).mas_offset(-10);
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-80);
        make.height.width.mas_equalTo(65);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [weakSelf.view layoutIfNeeded];
    }];
}


- (void)productListControllerHiddenButton:(YLProductListController *)controller
{
    __weak typeof(self) weakSelf = self;
    [_projectButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(weakSelf.view).mas_offset(-10);
        make.bottom.mas_equalTo(weakSelf.view).mas_offset(-80);
        make.height.width.mas_equalTo(65);
    }];
    
    double delayInSeconds = 3.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //执行事件
        [weakSelf.projectButton mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(weakSelf.view.mas_right).mas_offset(-10);
            make.bottom.mas_equalTo(weakSelf.view).mas_offset(-80);
            make.height.width.mas_equalTo(65);
        }];
        [UIView animateWithDuration:0.3 animations:^{
            [weakSelf.view layoutIfNeeded];
        }];
    });
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [WHProgressHUD dismiss];
}

- (void)qualificationSureViewSure:(YLQualificationSureView *)sureView
{
    [sureView removeFromSuperview];
    [self.pageTabView setSelectedTabIndexWithAnimation:1];
    YLFundListController *list = self.childViewControllers.lastObject;
    [list loadNewData];
}

- (void)pageTabViewDidEndChange {
    
    if (self.pageTabView.selectedTabIndex == 1) {
        YLAccount *account = [YLAccountTool account];
        if (account.fundQualifications == NO) {
            self.pageTabView.selectedTabIndex = 0;
            YLQualificationSureView *sureView = [[YLQualificationSureView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            sureView.delegate = self;
            [[UIApplication sharedApplication].keyWindow addSubview:sureView];
            return;
        }
        
        // 实认证失败 转去实名认证
        if ([YLAccountTool account].authState != 1) {
            self.pageTabView.selectedTabIndex = 0;
            YLCertifiedPaymentViewController *pay = [[YLCertifiedPaymentViewController alloc] init];
            pay.needToJumpTest = YES;
            [self.navigationController pushViewController:pay animated:YES];
        } else {
            
            if (![YLAccountTool account].isPassed) {
                self.pageTabView.selectedTabIndex = 0;
                
                // 没有测评
                if ([YLAccountTool account].fundRiskGrade == 0) {
                    [self popRiskEvaluation:@"完成风险测评, 合理购买基金产品"];
                } else {
                    [self popRiskEvaluation:@"风险测评等级过低, 建议重新评测"];
                }
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
